﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Iorz.DomainSearch.Utils.Provider;

namespace Iorz.DomainSearch
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<IProvider> mProviders = null;

        private Domain mDomainHandler = null;

        private double mTotalCount = 0;
        private double mCompleteCount = 0;

        public MainWindow()
        {
            InitializeComponent();

            mProviders = GetProviders();
            foreach (var provider in mProviders)
            {
                CheckBox checkBox = new CheckBox();
                checkBox.Content = provider.GetName();
                checkBox.Tag = provider;
                this.panelProvider.Children.Add(checkBox);
            }

            mTotalCount = Domain.CalculateCount(this.txtDomains.Text, this.txtDomainLength.Text);
            SetCount();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("确定是退出吗？", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.No)
                e.Cancel = true;
            else
                mDomainHandler?.StopWorker();
        }

        private void txtDomainLength_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (mProviders == null) return;

            mTotalCount = Domain.CalculateCount(this.txtDomains.Text, this.txtDomainLength.Text);
            SetCount();
        }

        private void txtDomains_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (mProviders == null) return;

            mTotalCount = Domain.CalculateCount(this.txtDomains.Text, this.txtDomainLength.Text);
            SetCount();
        }

        private void txtFormat_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (mProviders == null) return;

            var format = this.txtFormat.Text.Trim().Replace("{domain}", string.Empty);
            this.txtFormatLength.Text = format.Length.ToString();
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            mCompleteCount = 0;
            SetCount();

            var providers = GetSelectedProviders();
            if (providers.Count <= 0)
            {
                MessageBox.Show("请选择域名提供商");
                return;
            }

            var format = this.txtFormat.Text.Trim();
            if (string.IsNullOrEmpty(format) || format.IndexOf("{domain}") == -1)
            {
                MessageBox.Show("请填写域名格式，且需包含替换符{domain}");
                return;
            }

            var domainLength = 0;
            if (string.IsNullOrEmpty(this.txtDomainLength.Text) || !int.TryParse(this.txtDomainLength.Text, out domainLength))
            {
                this.txtDomainLength.Text = string.Empty;
                MessageBox.Show("域名长度为数字");
                return;
            }

            mDomainHandler = new Domain(this.Dispatcher, providers);
            mDomainHandler.Search(this.txtDomains.Text.Trim().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), format, domainLength, (result, message, domain) =>
            {
                mCompleteCount++;
                this.txtLog.Text = $"【{domain}】{message}{Environment.NewLine}" + this.txtLog.Text;
                SetCount();
            }, () =>
            {
                MessageBox.Show("搜索完成！");
                this.btnStart.IsEnabled = true;
                this.btnStop.IsEnabled = false;
            });

            this.btnStart.IsEnabled = false;
            this.btnStop.IsEnabled = true;
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            mDomainHandler?.StopWorker();

            this.btnStart.IsEnabled = true;
            this.btnStop.IsEnabled = false;
        }

        private List<IProvider> GetProviders()
        {
            var list = new List<IProvider>();
            list.Add(new AliyunProvider());
            list.Add(new BaiduProvider());
            list.Add(new WestProvider());
            list.Add(new CndnsProvider());
            list.Add(new XinnetProvider());
            list.Add(new GodaddyProvider());

            return list;
        }

        private List<IProvider> GetSelectedProviders()
        {
            var list = new List<IProvider>();
            foreach (Control item in this.panelProvider.Children)
            {
                if (item is CheckBox && ((CheckBox)item).IsChecked.HasValue && ((CheckBox)item).IsChecked.Value)
                {
                    list.Add((IProvider)item.Tag);
                }
            }
            return list;
        }

        private void SetCount()
        {
            this.lblCount.Content = $"{mTotalCount}/{mCompleteCount}";
        }
    }
}
